#!/usr/bin/env ruby

require "fanfou"


MSG = <<END

Usage: #{$0} path/to/fanfou/archive[.zip] all|safe [-z]
   all: Save all your messages to database.
   safe: Save all your messages except private messages to database.
   -z: If you are on *nix, you can use this option with a zip archive;
       If you are using windows, please extract your archive first.
  
If you specify any other options, it will be just use "all".

END

def do_it(url, argv)
  begin
    p = Fanfou::Parser.new(url)
    argv[1] ||= ""
    argv[1].downcase == "safe" ? p.parse_safe : p.parse_all
    puts "Success, please upload 'fanfou' folder to you web_root, and enjoy."
  rescue Fanfou::WrongPathError => e
    puts e.message
    puts MSG
  rescue StandardError => e
    puts e.message
    puts "Unknow error!"
  end
  
  photo_path = File.join(url, "photo")
  static_path = File.join(url, "static")
  thumb_path = File.join(url, "thumb")
  
  dst_photo_path = File.join("fanfou", "photo")
  dst_static_path = File.join("fanfou", "static") 
  dst_thumb_path = File.join("fanfou", "thumb")
  
  if(ENV['OS'] == "Windows_NT")
    system("ruby fileop.rb #{url}")
    system("copy fanfou.sqlite3 fanfou")
    system("move #{photo_path} fanfou")
    system("move #{static_path} fanfou")
    system("move #{thumb_path} fanfou")
    url = url.gsub(/\//, '\\') # A work around for windows platform.
    system("rd /s /q #{url}")
  else
    system("ruby fileop.rb #{url}")
    system("mv fanfou.sqlite3 fanfou")
    system("cp -R #{photo_path} #{dst_photo_path}")
    system("cp -R #{static_path} #{dst_static_path}")
    system("cp -R #{thumb_path} #{dst_thumb_path}")
    system("rm -rf #{url}")
  end
end

if ARGV[0].nil?
  puts msg
  exit 1
elsif ARGV[2] == '-z'
  unless File.file? ARGV[0]
    puts "Please use -z with a zip file!"
    exit 1
  end
  if File.expand_path(File.dirname(ARGV[0])) == File.expand_path(File.dirname(__FILE__))
      puts "Please put the zip file somewhere else!"
      exit 1
  end
  if system("unzip -q #{ARGV[0]} -d #{File.dirname(ARGV[0])}")
    url = File.join(File.dirname(ARGV[0]), "fanfou")
    do_it(url, ARGV)
  else
    puts "Extract failed, are you sure you are on *nix and specify the correct zip filename?"
    exit 1
  end
else
  url = ARGV[0]
  if File.file? ARGV[0]
    puts "Please use -z with a zip file!"
    exit 1;
  end
  do_it(url, ARGV)
end
